class ApplicationController < ActionController::Base



 
  #FILTRO 1 - internationalization
  before_filter :set_i18n_locale_from_params
  
  #FILTRO 2 - authentication
  before_filter :authorize
  
  #?
  protect_from_forgery

  private

    #CART
    def current_cart 
      Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      cart = Cart.create
      session[:cart_id] = cart.id
      cart
    end

    # ...

  protected

    def authorize
      if request.format == Mime::HTML 
        unless User.find_by_id(session[:user_id])
          redirect_to login_url, notice: "Please log in"
        end
      else
        authenticate_or_request_with_http_basic do |username, password|
          user = User.find_by_name(username)
          user && user.authenticate(password)
        end
      end
    end

	# i18n
    def set_i18n_locale_from_params
      if params[:locale]
        if I18n.available_locales.include?(params[:locale].to_sym)
          I18n.locale = params[:locale]
        else
          flash.now[:notice] = 
            "#{params[:locale]} translation not available"
          logger.error flash.now[:notice]
        end
      end
    end
	
    def default_url_options
      { locale: I18n.locale }
    end
	
#before_filter :set_locale

# def set_locale
  # I18n.locale = extract_locale_from_tld || I18n.default_locale
# end
 
# Get locale from top-level domain or return nil if such locale is not available
# def extract_locale_from_tld
  # parsed_locale = request.host.split('.').last
  # I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale  : nil
# end	
end
